<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cu-bar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描机台" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
		</view>
		<view class="cu-bar search" style="padding: 10px" ref="cuBar" v-if="lineCode">
			<u-form style="width: 100%;">
				<u-form-item label="机台" prop="id" label-width="180" style="font-weight: 800;">
					<view>{{ lineCode}}</view>
				</u-form-item>
			</u-form>
		</view>
		<view v-show="currentRW">
			<scroll-view
				scroll-y="true"
				@scrolltolower="loadMore"
				:refresher-enabled="true"
				:scrolltolower-enabled="true"
				:refresher-triggered="triggered"
				@refresherrefresh="refresherrefresh"
				@scrolltoupper="refresherrefresh"
				class="scroll-view-class"
				:style="{ height: computedScrollViewHeight }"
			>
				<view class="cu-item shadow margin raduis" style="position: relative;" v-for="(item,index) in list">
					<view class="cu-form-group text-xl text-bold">
					<view class="title flex">
						<view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px;">
							{{ index + 1 }}
						</view>
						<view>异常类型：</view>
					</view>
					<view class="flex-sub"><js-select v-model="item.errorType" dict-type="mes_error_type" disabled></js-select></view>
					</view>
					<!-- <view class="cu-form-group">
						<view class="title">异常类型：</view>
						<view class="flex-sub">
							<js-select v-model="item.errorType" dict-type="mes_error_type" disabled></js-select>
						</view>
					</view> -->
					<view class="cu-form-group">
						<view class="title">异常描述：</view>
						<view class="flex-sub">{{ item.remarks }}</view>
					</view>	
					<view class="cu-form-group" style="color:#3E97B0 ;"  @click="readOnlyForm(item.id)">
						<view class="content-footer-right">查看详情</view>
						<u-icon name="arrow-right"></u-icon>
					</view>
					<view class="cu-form-group flex justify-end" v-if="item.status == 0">
						<button class="cu-btn lines-green shadow-blur" @click="deal(item.id)">
							<text class="cuIcon-writefill"></text> 异常处理
						</button>
					</view>			
				</view>
				<view v-if="list.length" class="loadmore" style="justify-self: flex-end">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
				<u-empty v-if="!list.length" style="height: 100%;"></u-empty>
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group">
				<!-- round -->
				<button class="cu-btn  bg-confirm lg margin-left " @click="add">新增</button>		
			</view>
		</view>
		<u-empty v-if="!currentRW" :style="{height: emptyViewHeight+'px'}"></u-empty>	
		<deal-form
			:modalName="modalName"
			@modalNameEmit="modalNameEmit"
			:daelId="daelId"
			@dealData="dealData"
			v-if="modalName == 'bottomModal'"
		></deal-form>
	</view>
</template>

<script>
	import dealForm from "./dealForm.vue"
	export default {
		components: {
			dealForm,
		},
		data() {
			return {
				focus:true,
				barCode:'',
				model: { },
				customStyle:{
					color:'red'
				},
				scrollViewHeight: 0,
				currentRW:false,
				emptyViewHeight:0,
				loadStatus: "loadmore",
				triggered: false,
				query: {
					pageNo: 1,
					pageSize: 20,
				// orderBy: "a.create_date desc",
				},
				list : [],
				modalName:null,
				lineCode:'',
				daelId:''
			}
		},
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		// onLoad(){
		// 	this.loadData();
		// },
		onShow(){
			this.loadData();
		},
		methods:{
			readOnlyForm(id){
				uni.navigateTo({
					url: "/pages/mes/yichang/readOnlyForm?id=" + id 
				});
			},
			dealData(e){
				console.log(e,'dealData')
				this.$u.api.kst.mesLineErrorDeal(e.dealData).then(res=>{
					if(res.result == "true"){
						this.$u.toast("处理成功");
						this.loadData();
					}else{
						this.$refs.jsError.showError('',res.message,'error');
					}
				})
			},
			deal(id){
				this.daelId = id
				this.modalName = "bottomModal";
			},
			modalNameEmit(e) {
				this.modalName = e;
			},
			add(){
				uni.navigateTo({
					url: "/pages/mes/yichang/form?lineCode=" + this.lineCode 
				});
			},

			async refresherrefresh() {
				this.triggered = true;
				this.query.pageNo = 1;
				await this.loadData();
				setTimeout(() => {
					this.triggered = false;
				}, 500);
			},
			loadMore() {
				this.loadStatus = "loading";
				setTimeout(() => {
					this.query.pageNo += 1;
					this.loadData("add");
				}, 100);
			},
			loadData(type) {
				this.query.lineCode = this.lineCode
				this.$u.api.kst.mesLineErrorListData(this.query).then((res) => {
					if (res.list.length < 20 || res.list.length == 0) {
					this.loadStatus = "nomore";
					}
					var data = res.list;
					if (type == "add") {
					for (var i = 0; i < data.length; i++) {
						this.list.push(data[i]);
					}
					} else {
					this.list = data;
					}
				});
			},
			async calculateScrollViewHeight() {
			  try {
					// 等待头部高度计算完成
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 0 : 0;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0;
				  console.log(screenHeight,btnOffsetHeight,cuBarOffsetHeight,'===')
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( btnOffsetHeight + cuBarOffsetHeight + 80 );
			  } catch (error) {
			    	console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
			// 等待头部高度计算完成
			      
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0;
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			confirmSearch(){
				this.focus = false
				this.commonSearch(this.barCode)			
			},
			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				console.log(this.barCode.indexOf(JT),'JT',this.barCode,JT,this.barCode.indexOf(GP))
				if (barCode.indexOf(JT) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的机台",'error');
					setTimeout(() => {
						this.barCode = ''
						this.focus = true;
					}, 500);
					return;
				}else if(barCode.indexOf(JT) == 0){
					const res = await this.$u.api.kst.checkFunAndBar({
						funcType: this.vuex_config.JT,
						barJT: barCode
					});
					if (res.result == "true") {
						await this.$nextTick();
						this.barCode = '';
						this.lineCode = res.basLine.code;
						const resResult = await this.$u.api.kst.getTaskByLineCode({ lineCode: this.lineCode });

						if (resResult.result == "true") {
							this.currentRW = true;
							this.list = resResult.data;
							this.modid = this.list.length > 0 ? this.list[0]['modid'] : '';
							this.loadData();
							setTimeout(() => {
								this.focus = true;
							}, 500);
						}else{
							setTimeout(() => {
								this.focus = true;
							}, 500);
							this.$refs.jsError.showError('',resResult.message,'error');
						}
					} else {
						this.$u.toast(res.message);
						setTimeout(() => {
							this.focus = true;
						}, 500);
					}
				} 
			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearch(res.result)
					},
				});
			},
			onErrorClose(result) {
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
			 
			},
		}
	}	
</script>

<style scoped lang="scss">
	.title{
		width: 280rpx;
	}
	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
	.cu-bar.foot{
		z-index: 998 !important;
	}
	/deep/.u-drawer-content{
		height: 40% !important;
	}
</style>